package cn.wolfcode.trip.base.service.impl;


import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService{
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        Date date = new Date();
        StrategyContent strategyContent = strategyDetail.getStrategyContent();
        if(strategyDetail.getState() == StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(date);
        }
        if(strategyDetail.getId() == null){
            if(strategyDetail.getSequence() == null){
                Integer maxSequence = strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId());
                if (maxSequence == null) {
                    maxSequence = 0;
                }
                maxSequence ++;
                strategyDetail.setSequence(maxSequence);
            }
            strategyDetail.setCreateTime(date);
            strategyDetailMapper.insert(strategyDetail);
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.insert(strategyContent);
        }else {
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.update(strategyContent);
        }
    }


    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.queryForList(qo);
        return new PageInfo(list);
    }

    @Override
    public List<Map> listAll() {
        return null;
    }

    @Override
    public StrategyContent getContentById(Long strategyDetailId) {
        return strategyContentMapper.selectContentById(strategyDetailId);
    }

    @Override
    public StrategyDetail getStrategyDetail(Long id) {
        return  strategyDetailMapper.selectByPrimaryKey(id);
    }

    @Override
    public StrategyDetail selectById(Long detailsId) {
        return strategyDetailMapper.getStrategyContentById(detailsId);
    }

}
